package bc.running.forum.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


public abstract class HTMLUtils {
	public static List<String> getHTMLFraments(String msg) {
		List<String> result = new ArrayList<String>();
		Stack<Integer> openStack = new Stack<Integer>();
		List<FragmentOffsets> offsets = new ArrayList<FragmentOffsets>();
		for (int i = 0; i < msg.length(); i++) {
			if (msg.charAt(i) == '<' && msg.charAt(i) != '/') {
				openStack.push(i);
			}
			if (isClosingTag(i,msg) && !openStack.empty()) {
				FragmentOffsets fragmentOffsets = new FragmentOffsets(
						openStack.pop(), i);
				offsets.add(fragmentOffsets);
			}
		}
		for (FragmentOffsets fragmentOffsets : offsets) {
			String fragment = msg.substring(fragmentOffsets.start,
					fragmentOffsets.end + 1);
			result.add(fragment);
		}
		return result;
	}

	private static boolean isClosingTag(int index, String msg) {
		boolean  result = false;
		if (msg.charAt(index) == '>') {
			while (index > 1) {
				if (msg.charAt(index-1) == ' ') {
					result = false;
					break;
				}
				if (msg.charAt(index) == '/' && msg.charAt(index - 1) == '<') {
					result =  true;
					break;
				}
				index--;
			}
		} 
		return result;
	}

	private static class FragmentOffsets {
		public FragmentOffsets(int start, int end) {
			this.start = start;
			this.end = end;
		}

		int start;
		int end;
	}

	public static void main(String[] args) {
		String msg = "fbdfbdfbasdkfbadskflaslkfsndsdlfhasdfkndsfkadsf<table style=\"padding:0px; margin: 0px 0px 10px 0px; width:100%\" cellpadding=\"0\" cellspacing=\"0\" itemscope itemtype=\"http://schema.org/CreativeWork\"> dsifhasdfasjkdas;dhaso;dhfldsjfhadskfhdsjfhsdf<tr style=\"height: 58px;\">  <td id=\"plogo\">asdhsabfkjasdfbkasbdlaskfndasjfbasdkfbsadfsbdfksdf <link itemprop=\"url\" href=\"/p/sqlserver-to-mysqll\"> <a href=\"/p/sqlserver-to-mysqll/\">  <img src=\"http://www.gstatic.com/codesite/ph/images/defaultlogo.png\" alt=\"Logo\" itemprop=\"image\">  </a> </td>  <td style=\"padding-left: 0.5em\">  <div id=\"pname\"> <a href=\"/p/sqlserver-to-mysqll/\"><span itemprop=\"name\">sqlserver-to-mysqll</span></a> </div>  <div id=\"psum\"> <a id=\"project_summary_link\" href=\"/p/sqlserver-to-mysqll/\"><span itemprop=\"description\">Data migration from SQLServer to MySQL</span></a>  </div>   </td> <td style=\"white-space:nowrap;text-align:right; vertical-align:bottom;\">  <form action=\"/hosting/search\"> <input size=\"30\" name=\"q\" value=\"\" type=\"text\">  <input type=\"submit\" name=\"projectsearch\" value=\"Search projects\" > </form>  </tr> </table>";
		List<String> htmlFraments = HTMLUtils.getHTMLFraments(msg);
		StringBuilder xml = new StringBuilder("<root>");
		for (String fragment : htmlFraments) {
			System.out.println(fragment);
			xml.append(fragment);
		}
		xml.append("</root>");

	}

}
